#include <stdio.h>
#include <stdlib.h>
#include ".\nextperm.h"

typedef long long int64_t;

void print(const char* name, double *p, int n)
{
    printf("%s=", name);
    for (int i = 0; i < n; i++)
        printf("\t%.0f", *(p++));
    printf("\n");
}

int64_t factorial(int nn)
{
    int64_t p = 1;
    for (int ii = 2; ii <= nn; ii++)
        p *= ii;
    return p;
}

int main(int argc, char** argv)
{
    while (1)
    {
        int n;
        printf("Generate permutation of {1,2,...n}.\n\n");
        printf("Please input a number between 1 to 15: ");
        while (scanf("%d", &n))
        {
            if (n>0 && n<16)
                break;
            else
                printf("number should not larger than 15.\n");
            printf("Please input a number between 1 to 15: ");
        }
        
        double *p = (double *)malloc(sizeof(double)*n);
        for (int i = 0; i < n; i++)
            p[i] = i + 1;
        print("p", p, n);
        
        int s, N = 1;
        while (s = nextperm(p, n))
        {
            if (n<9)
                print("p", p, n);
            N += 1;
        }
        printf("\nn=%d; nn=%d; fact=%d\n", n, N, factorial(n));
        
        getchar();
        printf("\nQuit or continue? q/[c]: ");
        int c = getc(stdin);
        putchar('\n');
        if (c=='q' || c=='Q')
            break;
        
        free(p);
    }
}

